package com.cpit.qualitycontrol.web.controller;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.excel.ExportExcel;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.service.OperLogService;
import com.cpit.qualitycontrol.common.constant.LogConstantEx;
import com.cpit.qualitycontrol.entity.SubTaskReport;
import com.cpit.qualitycontrol.service.impl.ServiceUtils;
import com.cpit.qualitycontrol.service.impl.SubTaskReportServiceImpl;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/SystemReport")
public class SubTaskReportController {

    private final String loggerName = this.getClass().getName();

    @Autowired
    private SubTaskReportServiceImpl subTaskReportService = null;


    @Autowired
    private OperLogService operLogService;

    @ApiOperation(value = "查询工单任务", notes = "通过条件查询工单任务，返回List方式" +
            "支持模糊查询。")
    @ResponseBody
    //@PreAuthorize("hasAuthority('queryProcessRule')")
    @RequestMapping(value = "/querySubTaskReport", method = RequestMethod.GET)
    public List<SubTaskReport> querySubTaskReport(
            @ApiParam(value = "当前页数， 以1开始。") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "当前页的内容长度。") @RequestParam(value = "size", required = false, defaultValue = "20") int size,
            @ApiParam(value = "排序方式：asc为升序，desc为降序。") @RequestParam(value = "order", required = false, defaultValue = "asc") String order,
            @ApiParam(value = "排序字段，与dto中声明的字段名称一致。") @RequestParam(value = "orderBy", required = false, defaultValue = "id") String orderBy,
            @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
            @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "產品线Id") @RequestParam(value = "productLineId", required = false, defaultValue = "") Long productLineId,
            @ApiParam(value = "项目名称") @RequestParam(value = "projectName", required = false) String projectName,
            @ApiParam(value = "施工队") @RequestParam(value = "constructionTeamNames", required = false) String constructionTeamNames,

            @ApiParam(value = "工单类型") @RequestParam(value = "workOrderType", required = false) Long workOrderType) {
        return this.subTaskReportService.findByCondition(page, size, order, orderBy, beginTime, endTime, productLineId, projectName, constructionTeamNames, null, workOrderType);
    }

    @ResponseBody
    @RequestMapping(value = "/querySubTaskReportJqg", method = RequestMethod.GET)
    public TableJsonData querySubTaskReportJqg(TableDataQueryCondition cond) {

        LogOperator.debug(loggerName, "cond = [" + cond + "]");
        return this.subTaskReportService.findSubTaskByConditionJqg(ServiceUtils.getLoginUser().getId(), cond);
    }

    @ApiOperation(value = "导出报表", notes = "将系统中的报表导出到excel文件。")

    @RequestMapping(value = {"/exportreport"}, method = RequestMethod.GET)
    public String exportSubTaskReport( HttpServletRequest request, HttpServletResponse response,
                                      @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
                                      @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
                                      @ApiParam(value = "產品线Id") @RequestParam(value = "productLineId", required = false, defaultValue = "") Long productLineId,
                                      @ApiParam(value = "项目名称") @RequestParam(value = "projectName", required = false) String projectName,
                                      @ApiParam(value = "施工队") @RequestParam(value = "constructionTeamNames", required = false) String constructionTeamNames,
                                      @ApiParam(value = "工单类型") @RequestParam(value = "workOrderType", required = false) Long workOrderType
    )
    {
        String date = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");

        String fileName = "tSubTaskReport_" + date + ".xlsx";
        List<SubTaskReport> subTaskReportList = this.subTaskReportService.findAllByCondition(beginTime, endTime, productLineId, projectName, constructionTeamNames, null, workOrderType);

        try {
            int group = 0;
            if (workOrderType!=null){
                group = workOrderType.intValue();
            }
            ExportExcel exportExcel = new ExportExcel("报表信息", SubTaskReport.class, 1,group);
            exportExcel.setDatePattern("yyyy-MM-dd HH:mm:ss");
//
            exportExcel.setDataList(subTaskReportList).write(response, fileName).dispose();
            writeLog(LogConstant.OPER_EXPORT, Result.CODE_SUCCESS, fileName);
        } catch (Exception e) {
            LogOperator.err(loggerName, "export SubTaskReport info failed!", e);
            writeLog(LogConstant.OPER_EXPORT, Result.CODE_FAILED, e.getMessage());
        }
        return null;
    }


    /**
     * @param result
     * @param detail
     */
    private void writeLog(String op, String result, String detail) {
        OperLog operLog = new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setModule(LogConstantEx.MODULE_PROJECT);
        operLog.setCommand(op);
        operLog.setResult(result);
        operLog.setOperateUser(ServiceUtils.getLoginUser().getUsername());
        operLog.setDetail(detail);
        operLogService.writeLog(operLog);
    }
}
